package com.edgardeng.work_queues;

import com.edgardeng.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

/**
 * RabbitMQ 测试 Work Queues - 发布者发送消息
 *
 */
public class Sender {
    public static void main(String[] args) throws Exception{
        String queueName = ConnectionUtil.QUEUE_NAME_WORK_QUEUE;

        // 获取连接
        Connection connection = ConnectionUtil.getConnection();
        // 创建通道
        Channel channel = connection.createChannel();

        // 声明队列，如果不存在创建，否则不作为
        // arg1: 队列的名字
        // arg2: 是否持久化
        // arg3: 是否排外
        // arg4: 是否自动删除
        // arg5: 其他参数
        channel.queueDeclare(queueName, false,false,false,null);
        String message = "I'm sending Work Queues -- ";
        for (int i = 0; i < 100; i++) {
            // 发送内容100次
            channel.basicPublish("", queueName,null, (message + i).getBytes());
            System.out.println(" [x] Sent '" + message + i);
        }
        // 关闭连接
        channel.close();
        connection.close();

        /**
         * At this point we're sure that the task_queue queue won't be lost even if RabbitMQ restarts. Now we need to mark our messages as persistent - by setting MessageProperties (which implements BasicProperties) to the value PERSISTENT_TEXT_PLAIN.
         */
        // 消息持久化 重启后消息仍在
//        boolean durable = true;
//        channel.queueDeclare("task_queue", durable, false, false, null);
//        channel.basicPublish("", "task_queue",
//                MessageProperties.PERSISTENT_TEXT_PLAIN,
//                message.getBytes());
    }
}
